package tasks;

import java.util.Date;
import java.sql.Time;
import microcontroler.MicroControler;

import com.managment.data.Task;

public class TurnRoomLightOn extends Thread implements TaskThread{
	private Task task;
	private long delay;
	private MicroControler mc;
	private boolean repeatable = false;
	
	public TurnRoomLightOn(MicroControler mc){
		this.mc = mc;
	}
	
	public void initTask(){
		int task_time = 60*task.getEventTime().getHours()+task.getEventTime().getMinutes();
		Date now = new Date();
		int present_time = 60*now.getHours()+now.getMinutes();
		int full_time = 60*24;
		if(task_time < present_time)
			delay = (full_time-present_time+task_time)*60*1000;
		else
			delay = (task_time-present_time)*60*1000;
		long minutes = delay/60000;
		long delay_h = minutes/60;
		long delay_m = minutes%60;
		System.out.println("Światło w łazience zostanie zapalone za "+delay_h+" h "+delay_m+" min");
    	try {
			sleep(delay);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mc.turnLightOnInRoom();
		System.out.println("ZAPALENIE ŚWIATŁA - POKÓJ ("+new Date().toGMTString()+")");
	}
	
	private void repeatTask() {
		delay = 24*60*60*1000;
		System.out.println(new Date().toGMTString()+" ->Światło w pokoju zostanie zapalone za 24h");
		try {
			sleep(delay);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mc.turnLightOnInRoom();
		System.out.println("ZAPALENIE ŚWIATŁA - POKÓJ ("+new Date().toGMTString()+")");
	}
	
	public void run(){
	    while (true){
	    	initTask();
			
			if(repeatable){
				while(true)
					repeatTask();
			}else{
				//Usunięcie z bazy
				this.stop();
			}
	    }
	}
	public void setTask(Task task) {
		this.task = task;
	}
	public void setRepeatable(boolean repeatable){
		this.repeatable = repeatable;
	}
}
